<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="1200px" append-to-body custom-class="import-dialog"
               @close="close" ref="dialog"
    >
      <el-form :model="form" ref="form" inline label-width="100px">
        <el-form-item label="违约金：">
          <el-radio-group v-model="form.penaltyStates">
            <el-radio label="1">不收取</el-radio>
            <el-radio label="2">收取</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="比例：" v-if="form.penaltyStates == 2">
          <el-input v-model="form.penaltyScale" v-input.float="1"
                    @change="() => { form.penaltyScale = parseFloat(form.penaltyScale) }" style="width: 150px"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-table :data="list" style="width: 100%" :span-method="objectSpanMethod" ref="table" @expand-change="expandChange">
        <el-table-column label="期数" prop="billType">
          <template slot-scope="scope">
            <span v-if="scope.row.billType === '1'">押金</span>
            <span v-else-if="scope.row.billType === '2'">第{{ scope.row.periods }}期</span>
          </template>
        </el-table-column>
        <el-table-column label="总金额（元）" prop="cost">
          <template slot-scope="scope">
            <span v-if="scope.row.cost">{{ CalculateTotalAmount(scope.$index, scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column type="expand" width="20px">
          <template slot-scope="props">
            <div class="item-container" v-for="(item, index) in props.row.houseBillItemMerges" :key="index">
              <div class="item-container__item">
                <span>{{ item.itemName }}</span>
              </div>
              <div class="item-container__item">
                <div class="item-container__item__price">
                  <span v-if="!item.showEdit">{{ item.itemPrice.toFixed(2) }}</span>
                  <el-input v-else v-focus v-input.float="2" v-model="item.itemPrice" style="width: 100px"
                            @blur="() => { item.showEdit = false }" @change="(e)=>item.itemPrice = parseFloat(e)"
                  />
                </div>
                <el-button type="text" size="mini" @click="priceEdit(props.$index,index, item)" v-if="!item.showEdit"
                           icon="el-icon-edit"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="账单周期" prop="startTime">
          <template slot-scope="scope">
            <span>{{
                scope.row.billStartTime|formatDate('YYYY-MM-DD')
              }}至{{ scope.row.billEndTime|formatDate('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账单生成日期" prop="billCreateTime">
          <template slot-scope="scope">
            <span v-if="scope.row.billCreateTime">{{ scope.row.billCreateTime|formatDate('YYYY-MM-DD') }}</span>
            <span v-else>{{ genarateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最晚付款日期" prop="latestPayTime">
          <template slot-scope="scope">
            <span v-if="scope.row.latestPayTime">{{ scope.row.latestPayTime|formatDate('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="expand(scope.$index, scope.row)">
              {{ scope.row.expanded ? '收起' : '查看明细' }}
            </el-button>
          </template>
        </el-table-column>
        <!--        <el-table-column type="expand">-->
        <!--          <template slot-scope="props">-->
        <!--            <div class="item-container" v-for="(item, index) in props.row.houseBillItemMerges" :key="index">-->
        <!--              <div class="item-container__item">-->
        <!--                <span>{{ item.itemName }}</span>-->
        <!--              </div>-->
        <!--              <div class="item-container__item">-->
        <!--                <div class="item-container__item__price">-->
        <!--                  <span v-if="!item.showEdit">{{ item.itemPrice.toFixed(2) }}</span>-->
        <!--                  <el-input v-else v-focus v-input.float="2" v-model="item.itemPrice" style="width: 100px"-->
        <!--                            @blur="() => { item.showEdit = false }" @change="(e)=>item.itemPrice = parseFloat(e)"-->
        <!--                  />-->
        <!--                </div>-->
        <!--                <el-button type="text" size="mini" @click="priceEdit(props.$index,index, item)" v-if="!item.showEdit">-->
        <!--                  编辑-->
        <!--                </el-button>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">保 存</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from '@/utils'
import { calculateHouseBill } from '@/api/bill/houseBill'

export default {
  name: 'GenerateBill',
  props: {
    title: {
      type: String,
      default: '生成账单'
    },
    value: {
      type: Boolean,
      default: false
    },
    data: {
      // type: Array,
      default: {}
    }
  },
  data() {
    return {
      form: {},
      list: [],
      timeInterval: null,
      genarateTime: this.formatDate(new Date(), 'YYYY-MM-DD')
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)   // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
      }
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        } else {
          this.timeInterval && clearInterval(this.timeInterval)
        }
      },
      immediate: true
    }
  },
  methods: {
    init() {
      this.form = JSON.parse(JSON.stringify(this.data))
      this.calculateHouseBill()
      this.timeInterval = setInterval(() => {
        this.refreshTime()
      }, 1000 * 60)
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        return {
          rowspan: 1,
          colspan: 1
        }
      }else if (columnIndex !== 1 ) {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
      // return [1, 2]
    }
    ,
    // 展开行
    expand(index, row) {
      console.log(index, row)
      this.$refs.table.toggleRowExpansion(this.list[index])
      // this.list[index].expanded = !this.list[index].expanded
    },
    expandChange(row, status) {
      row.expanded = !row.expanded
      // console.log(row, status)
    },
    // 计算房屋账单
    calculateHouseBill() {
      calculateHouseBill(this.data).then(res => {

        if (res.code == 200) {
          this.list = res.data
        } else {
          this.$message.error(res.msg)
          this.visible = false
          this.$emit('error', res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
        this.visible = false
        this.$emit('error', err.msg)
      })
    }
    ,
    // 编辑价格
    priceEdit(index, cIndex, item) {
      this.$set(this.list[index].houseBillItemMerges[cIndex], 'showEdit', true)
    }
    ,
    // 计算总金额
    CalculateTotalAmount(index, row) {
      let total = 0
      row.houseBillItemMerges.forEach(item => {
        if (item.itemPrice) {
          item.itemPrice = item.itemPrice
        } else {
          item.itemPrice = 0
        }
        total += parseFloat(item.itemPrice)
      })
      return Number(total).toFixed(2)
    }
    ,
    // 刷新时间

    refreshTime() {
      console.log('refreshTime')
      return this.genarateTime = this.formatDate(new Date(), 'YYYY-MM-DD')
    }
    ,
    // 提交表单
    submit: debounce(function() {
      // this.list.map(item => {
      //   item.houseBillItemMerges.forEach(i => {
      //     this.form.houseBillList.push(i)
      //   })
      // })
      this.form.houseBillList = this.list
      this.$emit('submit', this.form)
      this.close()
    }, 500, true),
    close() {
      console.log('close')
      this.$emit('close')
      this.visible = false
    }
  }
}
</script>


<style scoped lang="scss">
.item-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  border-bottom: 1px solid #DFE6EB;
  padding: 10px 0;

  .item-container__item {
    display: flex;
    padding: 0 20px;
    align-items: center;


    .item-container__item__price {
      margin-right: 20px;
    }
  }

  &:where(.item-container:first-of-type) {
    padding-top: 0 !important;
  }

  &:where(.item-container:last-of-type) {
    border-bottom: none !important;
    padding-bottom: 0 !important;
  }
}

</style>
